import Axios from 'axios';
// import store from '@/store';
// import router from '@/router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { Message } from 'element-ui';
import { getUuid } from '@/utils/auth';
import { serialize } from '@/utils/util';

const request = Axios.create({
  baseURL: 'http://localhost:3000',
  timeout: 60000, // 请求超时60s
  // 配置响应成功的状态码范围
  validateStatus: function(status) {
    return status >= 200 && status < 600;
  },
  withCredentials: true // 跨域请求运行保存cookies
});

// const cancelToken = Axios.CancelToken;
// let source = cancelToken.source();
// source.token // 准备执行xhr.abort的promise对象
// source.cancel // 使上面promise对象完成的函数
// source = cancelToken.source(); // source.cancel();使用完后，需要再次赋值，不然source.token一直是完成态

// 把进度条的颜色更改为红色，轨迹颜色更改为绿色，宽度更改为3，并启用加载器
NProgress.configure({
  showSpinner: false // 关闭环状loading
});
// NProgress.set(0.5) // 设置进度条为50%

export const resTip = (res, failMsg = '操作失败') => {
  if (res && res.data) {
    let status = res.data.code;
    if (status !== 200 && res.config.responseType !== 'blob') {
      if (status === 401) {
        // store.dispatch("logOut").then(() => {
        //   router.push({path: "/login"});
        // });
      }
      Message.error(res.data.msg || failMsg);
    }
  } else {
    Message.error(failMsg);
  }
};

// 黑名单，在里面的接口，多次同时请求时，最后一次之前的请求会被取消
const blackNames = ['/goodsList'];

const getKey = (config) => {
  let { method, url } = config;
  if (blackNames.indexOf(url) > -1) {
    return [method, url].join('&');
  } else {
    return false;
  }
};

let penddingRequest = new Map();

function addPenddingRequest(config) {
  if (config) {
    const requestKey = getKey(config);
    if (!requestKey) return;
    config.cancelToken =
      config.cancelToken ||
      new Axios.CancelToken((cancel) => {
        if (!penddingRequest.has(requestKey)) {
          penddingRequest.set(requestKey, cancel);
        }
      });
  }
}
function removePenddingRequest(config) {
  if (config) {
    const penddingKey = getKey(config);
    if (!penddingKey) return;
    const cancelToken = penddingRequest.get(penddingKey);
    if (cancelToken) {
      penddingRequest.delete(penddingKey);
      cancelToken();
    }
  }
}

request.interceptors.request.use(
  (config) => {
    removePenddingRequest(config);
    addPenddingRequest(config);
    NProgress.start();
    // 设置请求头
    // config.headers["content-type"] = "application/json"; // Request Payload
    config.headers['Cache-Control'] = 'no-cache';
    config.headers['Authorization'] = 'Bearer ' + getUuid(); // 模拟携带token
    // 是否开启序列化
    let meta = config.meta || {};
    if (config.method === 'post' && meta.isSerialize === true) {
      config.data = serialize(config.data); // a=b&c=d&e=f
    }
    return config;
  },
  (err) => {
    NProgress.done();
    return Promise.reject(err);
  }
);

request.interceptors.response.use(
  (res) => {
    removePenddingRequest(res.config);
    NProgress.done();
    resTip(res);
    return res;
  },
  (err) => {
    removePenddingRequest(err.config);
    NProgress.done();
    return Promise.reject(err);
  }
);

export default request;
